package com.bgs.eat.userBack.service.impl;

import com.bgs.eat.area.entity.AreaEntity;
import com.bgs.eat.area.mapper.AreaMapper;
import com.bgs.eat.config.CommonResult;
import com.bgs.eat.page.MyPageHelper;
import com.bgs.eat.page.PageRequest;
import com.bgs.eat.page.PageResult;
import com.bgs.eat.userBack.entity.UserBackEntity;
import com.bgs.eat.userBack.mapper.UserBackMapper;
import com.bgs.eat.userBack.service.UserBackService;
import com.bgs.eat.utils.HttpUtils;
import com.bgs.eat.utils.RedisUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @ClassName UserBackServiceImpl
 * @Description TODO
 * @Author cjl
 * @Date 2022/10/11 11:06
 **/
@Service
public class UserBackServiceImpl implements UserBackService {

    @Autowired(required = false)
    UserBackMapper userBackMapper;

    /**
    * @Author cjl
    * @Description 后台登录
    * @Date  11:25
    * @Return com.bgs.eat.config.CommonResult
    * @param userBackEntity
    */
    @Override
    public CommonResult userBackDengLu(UserBackEntity userBackEntity) {
        String md5Password = DigestUtils.md5DigestAsHex(userBackEntity.getPassword().getBytes());
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("loginName",userBackEntity.getLoginName())
                                .andEqualTo("password",md5Password)
                                .andEqualTo("delFlag",0);
        UserBackEntity userBackEntity1 = userBackMapper.selectOneByExample(example);
        if (userBackEntity1 !=null){
            String token = UUID.randomUUID().toString().replace("-", "");
            Example example1 = new Example(UserBackEntity.class);
            example1.createCriteria().andEqualTo("id",userBackEntity1.getId());
            userBackEntity1.setToken(token);
            userBackMapper.updateByExampleSelective(userBackEntity1,example);
            return CommonResult.ok(userBackEntity1);
        } else {
            return CommonResult.error("100","登录失败");
        }
    }

    /**
    * @Author cjl
    * @Description 后台用户全查（模糊查）
    * @Date  15:51
    * @Return com.bgs.eat.page.PageResult
    * @param userName
    * @param pageRequest
    */
    @Override
    public PageResult selectUserBackEntity(String userName, PageRequest pageRequest) {
        if (StringUtils.isEmpty(userName)){
            userName="";
        }
        MyPageHelper.startPage(pageRequest);
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andLike("userName","%"+userName+"%")
                .andEqualTo("delFlag",0);
        List<UserBackEntity> userBackEntityList = userBackMapper.selectByExample(example);
        return MyPageHelper.pageInfo(userBackEntityList);

    }

    /**
    * @Author cjl
    * @Description 后台用户添加或修改
    * @Date  15:55
    * @Return int
    * @param userBackEntity
    */
    @Override
    public int saveOrUpdateUserBackEntity(UserBackEntity userBackEntity) {
        int i = 0;
        if (userBackEntity.getId()==0){
            String md5Password = DigestUtils.md5DigestAsHex("1".getBytes());
            userBackEntity.setPassword(md5Password);
            userBackEntity.setCreateTime(new Date());
            userBackEntity.setUpdateTime(new Date());
            userBackEntity.setDelFlag(0);
            i = userBackMapper.insertSelective(userBackEntity);
        } else {
            userBackEntity.setUpdateTime(new Date());
            i = userBackMapper.updateByPrimaryKeySelective(userBackEntity);
        }
        return i;
    }



    /**
    * @Author cjl
    * @Description 后台用户删除
    * @Date  8:49
    * @Return java.lang.Integer
    * @param id
    */
    @Override
    public Integer deleteUserBackEntityById(Integer id) {
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("id",id);
        UserBackEntity userBackEntity = new UserBackEntity();
        userBackEntity.setDelFlag(1);
        int i = userBackMapper.updateByExampleSelective(userBackEntity, example);
        return i;
    }

    /**
    * @Author cjl
    * @Description 单查后台用户详情 （个人详情）
    * @Date  20:51
    * @Return com.bgs.eat.userBack.entity.UserBackEntity
    * @param id
    */
    @Override
    public UserBackEntity selectUserBackById(Integer id) {
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("id",id);
        UserBackEntity userBackEntity = userBackMapper.selectOneByExample(example);
        return userBackEntity;
    }

    /**
    * @Author cjl
    * @Description 修改后台用户详情 （个人详情）
    * @Date  16:00
    * @Return int
    * @param userBackEntity
    */
    @Override
    public int updateUserBackEntityInfo(UserBackEntity userBackEntity) {
        int i = userBackMapper.updateByPrimaryKeySelective(userBackEntity);
        return i;
    }

    /**
    * @Author cjl
    * @Description 修改后台当前用户密码
    * @Date  16:00
    * @Return com.bgs.eat.config.CommonResult
    * @param map
    */
    @Override
    public CommonResult userBackUpdatePassword(Map<String, String> map) {
        // 取出map里面的旧密码，密码，确认密码，id
        String oldPassword = map.get("oldPassword");
        String password = map.get("password");
        String confirmkPassword = map.get("confirmkPassword");
        String id = map.get("confirmkPassword");
        // 加密旧密码
        String md5OldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        // 通过id查询 当前id用户的密码
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("id",id);
        UserBackEntity userBackEntity = userBackMapper.selectOneByExample(example);
        // 判断加密后的旧密码和数据库里当前id用户的密码是否相等
        if (md5OldPassword.equals(userBackEntity.getPassword())){
            // 判断map里面的密码和map里面的确认密码是否相等
            if(password.equals(confirmkPassword)){
                // 加密map里面的密码
                String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
                // 修改当前用户的密码
                Example example1 = new Example(UserBackEntity.class);
                example1.createCriteria().andEqualTo("id",id);
                UserBackEntity userBackEntity1 = new UserBackEntity();
                userBackEntity1.setPassword(md5Password);
                userBackMapper.updateByExampleSelective(userBackEntity1, example1);
                return CommonResult.ok("修改密码成功，请重新登录");
            } else {
                return CommonResult.error("102","密码和确认密码不匹配，请重新输入");
            }
        } else {
            return CommonResult.error("101","旧密码不正确，请重新输入");
        }
    }

    @Autowired
    AreaMapper areaMapper;
    /**
     * @Author cjl
     * @Description 查询省
     * @Date  14:02
     * @Return com.bgs.eat.config.CommonResult
     */
    @Override
    public CommonResult userBackEntityProvince() {
        Example example = new Example(AreaEntity.class);
        example.createCriteria().andEqualTo("level",1);
        List<AreaEntity> areaEntities = areaMapper.selectByExample(example);
        return CommonResult.ok(areaEntities);
    }
    /**
     * @Author cjl
     * @Description 通过省id 查市
     * @Date  14:03
     * @Return com.bgs.eat.config.CommonResult
     * @param provinceId
     */
    @Override
    public CommonResult userBackEntityCity(Integer provinceId) {
        Example example = new Example(AreaEntity.class);
        example.createCriteria().andEqualTo("level",2)
                .andEqualTo("pid",provinceId);
        List<AreaEntity> areaEntities = areaMapper.selectByExample(example);
        return CommonResult.ok(areaEntities);
    }
    /**
     * @Author cjl
     * @Description 通过省id 查县
     * @Date  14:03
     * @Return com.bgs.eat.config.CommonResult
     * @param cityId
     */
    @Override
    public CommonResult userBackEntityCounty(Integer cityId) {
        Example example = new Example(AreaEntity.class);
        example.createCriteria().andEqualTo("level",3)
                .andEqualTo("pid",cityId);
        List<AreaEntity> areaEntities = areaMapper.selectByExample(example);
        return CommonResult.ok(areaEntities);
    }

    /**
    * @Author cjl
    * @Description 查询登录名称不能重复
    * @Date  18:35
    * @Return com.bgs.eat.config.CommonResult
    * @param loginName
    */
    @Override
    public CommonResult selectUserBackEntityByLoginName(String loginName) {
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("loginName",loginName)
                                .andEqualTo("delFlag",0);
        UserBackEntity userBackEntity = userBackMapper.selectOneByExample(example);
        return CommonResult.ok(userBackEntity);
    }

    @Autowired
    RedisUtil redisUtil;

    /**
     * @Author cjl
     * @Description 后端用户 发送手机验证码
     * @Date 2022/11/1 13:37
     * @Return com.bgs.eat.config.CommonResult
     * @param map
     */
    @Override
    public CommonResult userBackVerificationCode(Map<String, String> map) {
        String phone = map.get("phone");
        String codeMark = map.get("codeMark");
        Example example = new Example(UserBackEntity.class);
        example.createCriteria().andEqualTo("phone",phone)
                                .andEqualTo("delFlag",0);
        UserBackEntity userBackEntity = userBackMapper.selectOneByExample(example);
        if(userBackEntity != null){
//            String host = "https://gyytz2.market.alicloudapi.com";
//            String path = "/sms/smsSendLong";
//            String method = "POST";
//            String appcode = "a725f268bf1a4834878cad3d37917dd1";
//            Map<String, String> headers = new HashMap<String, String>();
//            headers.put("Authorization", "APPCODE " + appcode);
//            Map<String, String> querys = new HashMap<String, String>();
//            querys.put("mobile", phone);
//            querys.put("param", "**code**:123456,**minute**:5");
//            querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
//            querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
//            Map<String, String> bodys = new HashMap<String, String>();
//            try {
//                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//                System.out.println(response.toString());
//                redisUtil.set(phone + codeMark, "123456", 300);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return CommonResult.ok();

            redisUtil.set(phone + codeMark, "147258", 300);
            return CommonResult.ok();
        }else {
            return CommonResult.error("888","账号不存在");
        }


    }

    /**
     * @Author cjl
     * @Description 后端用户验证码登录
     * @Date 2022/11/1 13:37
     * @Return com.bgs.eat.config.CommonResult
     * @param map
     */
    @Override
    public CommonResult userBackPhoneLogin(Map<String, String> map) {
        String phone = map.get("phone");
        String codeMark = map.get("codeMark");
        String verificationCode = map.get("verificationCode");
        Object redisCodeMark = redisUtil.get(phone + codeMark);
        System.out.println(redisCodeMark);
        if (redisCodeMark!=null&&!redisCodeMark.equals(null)){
            if (verificationCode.equals(redisCodeMark)){
                return CommonResult.ok("恭喜你，登录成功");
            } else {
                return CommonResult.error("888","验证码不正确");
            }
        } else {
            return CommonResult.error("999","登录超时，请重新发送验证码");
        }
    }


}
